﻿/*
 * @Autor: PK
 * @Date: 2022/01/28 10:24:SS
 */

using System.Data;
using ShkSimulation.core.dao.input.loader;
using ShkSimulation.core.dao.input.resource;
using ShkSimulation.desktop.setting;
using ShkSimulation.carsharing.impl;
using DataTable = System.Data.DataTable;

namespace ShkSimulation.desktop.component.tools {

	public class RealTimePerformanceStatisticsTool: ResetSimulation {

		private SimulationApplication application;

		private DataTable dataTable;
		private int runSecondCount;

		public RealTimePerformanceStatisticsTool(bool enable = false) {
			SetEnabled(enable);
		}

		public bool Enabaled { get; private set; }

		public void SetSimulationApplication(SimulationApplication app) {
			Reset();
			this.application = app;
			application.BeforeSimulationRun += BeforeSimulationRun;
		}
		
		public void Reset() {
			dataTable?.Clear();
			dataTable = new DataTable();
			if (application != null) {
				application.BeforeSimulationRun -= BeforeSimulationRun;
			}
			application = null;
			dataTable.Columns.Add("时间（秒）", typeof(double));
			dataTable.Columns.Add("仿真推进时长（天）", typeof(double));
			dataTable.Columns.Add("每秒推进时长（天/秒）", typeof(double));
		}

		public bool Export(string filePath, ResourceLoader loader = null) {
			loader = loader ?? new ExcelResourceLoader();
			Resource resource = new DefaultDataTableResource("仿真进度数据", dataTable, ResourceType.Excel, filePath);
			return loader.SaveData(resource);
		}

		private void BeforeSimulationRun(SimulationInfo app) {
			if (ConfigManager.UserRunConfig.真实时间) {
				application.OnSimulationRunning += SimulationRunning;
				application.AfterRunCompleted += AfterRunCompleted;
			}
			AddRecord(0, 0);
			runSecondCount = 1;
		}

		private void SimulationRunning(SimulationInfo app) {
			double totalDays = (app.Network.NetworkCurrentTime - app.Network.NetworkStartTime).TotalDays;
			double runSeconds = ConfigManager.UserRunConfig.观察间隔.TotalSeconds * runSecondCount;
			AddRecord(runSeconds, totalDays);
			runSecondCount++;
		}
		
		private void AfterRunCompleted(SimulationInfo app) {
			double totalDays = (app.Network.NetworkCurrentTime - app.Network.NetworkStartTime).TotalDays;
			AddRecord(ConfigManager.UserRunConfig.仿真时长.TotalSeconds, totalDays);
		}

		private void AddRecord(double realTime, double simulationTime) {
			DataRow row = dataTable.NewRow();
			row[0] = realTime;
			row[1] = simulationTime;
			if (realTime == 0) {
				row[2] = 0;
			} else {
				row[2] = simulationTime / realTime;
			}
			dataTable.Rows.Add(row);
		}

		public void SetEnabled(bool enabled) {
			this.Enabaled = enabled;
			if (!enabled) {
				this.Reset();
			}
		}

	}

}